import json

from django.http import JsonResponse
from django.views import View
from app.models import Salary_college, Salary_theme, User


class SalaryCollege(View):
    def post(self, req):
        d = json.loads(req.body)
        u_id = d["id"]
        # salary_id = d["salary_theme_id"]
        # d.pop("user_id")
        # d.pop("salary_theme_id")
        Salary_college.objects.filter(user_id=u_id).update(**d)
        return JsonResponse({"code": 200, "message": "生成成功"})

    def get(self, req):
        page = int(req.GET.get("page",''))
        pagesize = int(req.GET.get("pagesize"))
        salary_theme = req.GET.get("salary_theme", "")
        keyword = req.GET.get("keyword", "")
        start = (page - 1) * pagesize
        end = page * pagesize
        Salary_colleges=list(Salary_theme.objects.get(id=salary_theme).salary_college_set.filter(user__name__contains=keyword)[start:end].values())
        total = Salary_theme.objects.get(id=salary_theme).salary_college_set.filter(user__name__contains=keyword).count()
        for i in Salary_colleges:
            Userinfo=list(User.objects.filter(id=i['user_id']).values(
                "name","department__name","entry_time",
                "job",'user_state','basic_wage','accumulation',
                'provide_insurance','medical_insurance','unemployment_insurance',
                'regular_time'
            ))
            for j in Userinfo[0]:
                i[j]=Userinfo[0][j]
        return JsonResponse({"code": 200, "message": "获取成功", "data": Salary_colleges,"total":total})
        # return JsonResponse({"code": 200, "message": "获取成功"})

    def put(self, req):
        data = json.loads(req.body)
        for key in [ "name","department__name","entry_time",
                "job",'user_state','basic_wage','accumulation',
                'provide_insurance','medical_insurance','unemployment_insurance']:
            data.pop(key)
        Salary_college.objects.filter(id=data["id"]).update(**data)
        return JsonResponse({"code": 200, "message": "修改成功"})

    def delete(self, req):
        return JsonResponse({"code": 200, "message": "添加成功"})
